/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.farmcode.base.manager;

import com.farmcode.base.dao.BaseDAO;
import com.farmcode.base.dao.BaseFilter;
import com.farmcode.base.dao.DAOException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

/**
 *
 * @author oiprado
 */
public class BaseManagerImpl <T extends BaseDAO<J>, J> implements BaseManager<T, J> {
   
  private T baseDAO;

  public BaseManagerImpl() {
    
  }

  public BaseManagerImpl(String name) {
    System.out.println(name);
    baseDAO = lookupEJB(name);
  }
  
  @Override
  public void create(J entity) throws FacadeException {
    try {
      baseDAO.create(entity);
    } catch (DAOException ex) {
      throw wrapException(ex);
    }
  }

  @Override
  public void store(J entity) throws FacadeException {
     try {
      baseDAO.create(entity);
    } catch (DAOException ex) {
      throw wrapException(ex);
    }
  }

  @Override
  public void remove(J entity) throws FacadeException {
     try {
      baseDAO.create(entity);
    } catch (DAOException ex) {
      throw wrapException(ex);
    }
  }

  @Override
  public List<J> find() throws FacadeException {
     try {
      return baseDAO.find();
    } catch (DAOException ex) {
      throw wrapException(ex);
    }
  }

  @Override
  public void setBaseFilter(BaseFilter baseFilter) {
    baseDAO.setFilter(baseFilter);
  }
  
  protected FacadeException wrapException(Exception ex) {
    return new FacadeException(ex);
  }

  private T lookupEJB(String name) {
    try {
      Context c = new InitialContext();
      Object proxy = c.lookup(name);
      System.out.println("Proxy: "+proxy);
      return (T) proxy;
    } catch (NamingException ne) {
      Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
      throw new RuntimeException(ne);
    }
  }
  
}
